import os
import re
from contextlib import AsyncExitStack
from typing import Optional

from openai import OpenAI
from dotenv import load_dotenv
from mcp import ClientSession, StdioServerParameters

load_dotenv()


class McpClient:

    def __init__(self):
        self.exit_stack = AsyncExitStack()
        self.api_key = os.getenv("DASHSCOPE_API_KEY")
        self.base_url = os.getenv("DASHSCOPE_BASE_URL")
        self.model_name = os.getenv("DASHSCOPE_MODEL_NAME")
        if not self.api_key:
            raise ValueError("api key is not set")
        self.client = OpenAI(api_key=self.api_key, base_url=self.base_url, model_name=self.model_name)
        self.session = Optional[ClientSession] = None

    async def connect_to_server(self, server_script_path: str):
        # 对服务器脚本进行判断，必须是python或者js文件
        is_python = server_script_path.endswith(".py")
        is_js = server_script_path.endswith(".js")
        if not (is_python or is_js):
            raise ValueError("server script path must end with .py or .js")

        # 确定启动命令，根据文件类型选择python或者node
        command = ""
        if (is_python):
            command = "python"
        else:
            command = "node"

        # 构建MCP所需的服务器参数，包含启动命令、脚本路径、环境变量（默认为None）
        server_params = StdioServerParameters(
            command=command,
            args=[server_script_path],
            env=None,
        )




